package com.alibaba.citrus.ots.sales.plan.repository;

import com.alibaba.citrus.ots.common.annotation.RepositoryInvoker;
import com.alibaba.citrus.ots.common.exception.FacadeException;
import com.alibaba.citrus.ots.common.util.CalculatePercentage;
import com.alibaba.citrus.ots.sales.plan.converter.PlanCustomerConverter;
import com.alibaba.citrus.ots.sales.plan.dto.api.request.PageQueryPlanCustomerStatRequest;
import com.alibaba.citrus.ots.sales.plan.dto.api.request.QueryPlanCustomerStatRequest;
import com.alibaba.citrus.ots.sales.plan.dto.api.request.SalesPlanStatCustomerSubTotalRequest;
import com.alibaba.citrus.ots.sales.plan.dto.api.response.SalesPlanScItemStatSubTotalResponse;
import com.alibaba.citrus.ots.sales.plan.dto.api.response.SalesPlanStatCustomerSubTotalResponse;
import com.alibaba.citrus.ots.sales.plan.model.SalesPlanCustomerStatusEnum;
import com.alibaba.citrus.ots.sales.plan.model.enums.SalesStatBizTypeEnum;
import com.alibaba.citrus.ots.sales.plan.model.features.SalesPlanCustomerFeatures;
import com.alibaba.citrus.ots.sales.plan.repository.request.QueryPlanCustomerByAddressRequest;
import com.alibaba.citrus.ots.sales.plan.repository.request.SalesPlanStatCustomerSubTotalRepoRequest;
import com.alibaba.citrus.ots.sales.plan.sdo.SalesPlanStatCustomerSDO;
import com.alibaba.cz.base.tool.StringUtil;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcots.model.dto.PlanCustomerLoadListRequest;
import com.epoch.app.bcots.sales_plan.plancustomer.dto.BatchCreatePlanCustomerRequest;
import com.epoch.app.bcots.sales_plan.plancustomer.dto.BatchCreatePlanCustomerResponse;
import com.epoch.app.bcots.sales_plan.plancustomer.dto.BatchDeletePlanCustomerByPlanIdRequest;
import com.epoch.app.bcots.sales_plan.plancustomer.dto.BatchDeletePlanCustomerByPlanIdResponse;
import com.epoch.app.bcots.sales_plan.plancustomer.dto.CreatePlanCustomerResponse;
import com.epoch.app.bcots.sales_plan.plancustomer.dto.LoadPlanCustomerByCustomerAddressRequest;
import com.epoch.app.bcots.sales_plan.plancustomer.dto.LoadPlanCustomerRequest;
import com.epoch.app.bcots.sales_plan.plancustomer.dto.QueryPlanCustomerPercentRequest;
import com.epoch.app.bcots.sales_plan.plancustomer.dto.SubTotalSalesPlanStatCustomerRequest;
import com.epoch.app.bcots.sales_plan.plancustomer.dto.UpdatePlanCustomerResponse;
import com.epoch.app.bcots.sales_plan.plancustomer.model.PlanCustomer;
import com.epoch.app.bcots.sales_plan.plancustomer.service.PlanCustomerService;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author yuhailin
 * @description:
 * @date 2021-09-27 10:47
 */
@Component
public class SalesPlanCustomerStatRepositoryImpl implements SalesPlanCustomerStatRepository {
    @Resource
    PlanCustomerService planCustomerService;

    @Override
    @RepositoryInvoker(printLog = true)
    public String planCustomerSave(SalesPlanStatCustomerSDO salesPlanCustomerStatSDO) {
        PlanCustomer planCustomer = createPlanCustomerConverter(salesPlanCustomerStatSDO);
        try {
            CreatePlanCustomerResponse createPlanCustomerResponse = planCustomerService.createPlanCustomer(planCustomer);
            return createPlanCustomerResponse.getLastInsertId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    @RepositoryInvoker(printLog = true)
    public PageResult<List<SalesPlanStatCustomerSDO>> pageQueryPlanCustomerList(PageQueryPlanCustomerStatRequest pageQueryPlanCustomerStatRequest) {
        PlanCustomerLoadListRequest planCustomerLoadListRequest = planCustomerPageQueryStatRequestConverter(pageQueryPlanCustomerStatRequest);
        Result<List<PlanCustomer>> listResult = planCustomerService.loadPlanCustomerList(planCustomerLoadListRequest);
        List<SalesPlanStatCustomerSDO> collect = listResult.getResult().stream().map(planCustomer -> {
            SalesPlanStatCustomerSDO salesPlanCustomerStatSDO = new SalesPlanStatCustomerSDO();
            BeanUtils.copyProperties(planCustomer, salesPlanCustomerStatSDO);
            return salesPlanCustomerStatSDO;
        }).collect(Collectors.toList());
        return PageResult.of(collect, listResult.getTotal());
    }

    @Override
    @RepositoryInvoker(printLog = true)
    public SalesPlanStatCustomerSDO queryPlanCustomerByCustomerAddress(QueryPlanCustomerByAddressRequest request) {
        LoadPlanCustomerByCustomerAddressRequest build = LoadPlanCustomerByCustomerAddressRequest.builder()
                .planId(request.getPlanId())
                .customerCode(request.getCustomerCode())
                .customerAddress(request.getCustomerAddress())
                .build();
        Result<List<PlanCustomer>> listResult = planCustomerService.loadPlanCustomerByCustomerAddress(build);
        PlanCustomer planCustomer = null;
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(listResult.getResult())) {
            planCustomer = listResult.getResult().stream().findFirst().get();
        }
        return PlanCustomerConverter.planCustomerDoToSdo(planCustomer);
    }

    @Override
    @RepositoryInvoker(printLog = true)
    public Boolean updatePlanCustomer(SalesPlanStatCustomerSDO salesPlanCustomerStatSDO) {
        UpdatePlanCustomerResponse updatePlanCustomerResponse = planCustomerService.updatePlanCustomer(PlanCustomerConverter.planCustomerSdoToDo(salesPlanCustomerStatSDO));
        return updatePlanCustomerResponse != null && updatePlanCustomerResponse.getCount() != null && updatePlanCustomerResponse.getCount() > 0;
    }

    @Override
    @RepositoryInvoker(printLog = true)
    public boolean createPlanCustomer(SalesPlanStatCustomerSDO salesPlanCustomerStatSDO) {
        CreatePlanCustomerResponse customerResponse = planCustomerService.createPlanCustomer(PlanCustomerConverter.planCustomerSdoToDo(salesPlanCustomerStatSDO));
        return StringUtils.isNotEmpty(customerResponse.getLastInsertId());
    }

    @Override
    @RepositoryInvoker(printLog = true)
    public SalesPlanStatCustomerSDO getSalesPlanCustomer(QueryPlanCustomerStatRequest queryPlanCustomerStatRequest) {
        LoadPlanCustomerRequest loadPlanCustomerRequest = loadSalesPlanCustomerRequestConverter(queryPlanCustomerStatRequest);
        PlanCustomer planCustomer = planCustomerService.loadPlanCustomer(loadPlanCustomerRequest);
        SalesPlanStatCustomerSDO salesPlanCustomerStatSDO = new SalesPlanStatCustomerSDO();
        BeanUtils.copyProperties(planCustomer, salesPlanCustomerStatSDO);
        return salesPlanCustomerStatSDO;
    }

    @Override
    @RepositoryInvoker(printLog = true)
    public boolean batchCreatePlanCustomer(List<SalesPlanStatCustomerSDO> request) {
        BatchCreatePlanCustomerRequest customerRequest = new BatchCreatePlanCustomerRequest();
        customerRequest.setRequest(PlanCustomerConverter.planCustomerSdoToDo(request));
        BatchCreatePlanCustomerResponse batchCreatePlanCustomerResponse = planCustomerService.batchCreatePlanCustomer(customerRequest);

        return batchCreatePlanCustomerResponse != null && batchCreatePlanCustomerResponse.getCount() != null && batchCreatePlanCustomerResponse.getCount() == request.size();
    }

    @Override
    @RepositoryInvoker(printLog = true)
    public Boolean editSalesPlanCustomer(SalesPlanStatCustomerSDO salesPlanCustomerStatSDO) {
        PlanCustomer planCustomer = planCustomerConverter(salesPlanCustomerStatSDO);
        try {
            UpdatePlanCustomerResponse updatePlanCustomerResponse = planCustomerService.updatePlanCustomer(planCustomer);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("数据更新失败");
        }
        return true;
    }

    @Override
    @RepositoryInvoker(printLog = true)
    public Boolean deletePlanCustomerByPlanId(String planId) {
        BatchDeletePlanCustomerByPlanIdRequest request = new BatchDeletePlanCustomerByPlanIdRequest();
        request.setPlanId(planId);
        BatchDeletePlanCustomerByPlanIdResponse batchDeletePlanCustomerByPlanIdResponse = planCustomerService.batchDeletePlanCustomerByPlanId(request);
        return batchDeletePlanCustomerByPlanIdResponse != null && batchDeletePlanCustomerByPlanIdResponse.getCount() > 0;
    }

    @Override
    @RepositoryInvoker(printLog = true)
    public SalesPlanScItemStatSubTotalResponse subTotalSalesPlanStatCustomer(SalesPlanStatCustomerSubTotalRepoRequest salesPlanStatCustomerSubTotalRequest) {
        SubTotalSalesPlanStatCustomerRequest subTotalSalesPlanStatCustomerRequest = new SubTotalSalesPlanStatCustomerRequest();
        BeanUtils.copyProperties(salesPlanStatCustomerSubTotalRequest, subTotalSalesPlanStatCustomerRequest);
        PlanCustomer planCustomer = planCustomerService.subTotalSalesPlanStatCustomer(subTotalSalesPlanStatCustomerRequest);
        if (Objects.isNull(planCustomer)) {
            return null;
        }
        SalesPlanScItemStatSubTotalResponse response = new SalesPlanScItemStatSubTotalResponse();
        response.setMonthCount(planCustomer.getMonthCount());
        response.setBeforeMonthMoney(planCustomer.getBeforeMonthMoney());
        response.setMonthMoney(planCustomer.getMonthMoney());

        response.setMonthContractCount(planCustomer.getMonthContractCount());
        response.setBeforeMonthContractMoney(planCustomer.getBeforeMonthContractMoney());
        response.setMonthContractMoney(planCustomer.getMonthContractMoney());

        response.setTaskCount(planCustomer.getTaskCount());
        response.setBeforeTaskMoney(planCustomer.getBeforeTaskMoney());
        response.setTaskMoney(planCustomer.getTaskMoney());

        response.setAdjustCount(planCustomer.getAdjustCount());
        response.setBeforeAdjustMoney(planCustomer.getAdjustMoney());
        response.setAdjustMoney(planCustomer.getAdjustMoney());
        return response;
    }


    //Converter
    private PlanCustomer createPlanCustomerConverter(SalesPlanStatCustomerSDO salesPlanCustomerStatSDO) {
        PlanCustomer planCustomer = new PlanCustomer();
        BeanUtils.copyProperties(salesPlanCustomerStatSDO, planCustomer);
        SalesPlanCustomerFeatures salesPlanCustomerFeatures = new SalesPlanCustomerFeatures();
/*        salesPlanCustomerFeatures.setCustomerName(salesPlanCustomerStatSDO.getCustomerName());
        salesPlanCustomerFeatures.setBondType(salesPlanCustomerStatSDO.getBondType());
        salesPlanCustomerFeatures.setCustomerAddressName(salesPlanCustomerStatSDO.getCustomerAddressName());
*//*        salesPlanCustomerFeatures.setContactName(salesPlanCustomerStatSDO.getContactName());
        salesPlanCustomerFeatures.setCellphoneNumber(salesPlanCustomerStatSDO.getCellphoneNumber());*//*
        planCustomer.setFeatures(JSONObject.toJSONString(salesPlanCustomerFeatures));*/
        return planCustomer;
    }

    private PlanCustomerLoadListRequest planCustomerPageQueryStatRequestConverter(PageQueryPlanCustomerStatRequest pageQueryPlanCustomerStatRequest) {
        PlanCustomerLoadListRequest planCustomerLoadListRequest = new PlanCustomerLoadListRequest();
        BeanUtils.copyProperties(pageQueryPlanCustomerStatRequest, planCustomerLoadListRequest);
        if (pageQueryPlanCustomerStatRequest.getBizType() == null && StringUtil.isBlank(pageQueryPlanCustomerStatRequest.getBizId())) {
            throw new FacadeException("OTS-02-002-02-15-007");
        }
        SalesStatBizTypeEnum byOrganizationType = SalesStatBizTypeEnum.getByOrganizationType(pageQueryPlanCustomerStatRequest.getBizType());
        if (byOrganizationType == null) {
            throw new FacadeException("OTS-02-002-02-15-007");
        }
        switch (byOrganizationType) {
            case SALESMAN:
                planCustomerLoadListRequest.setManageEmployeeId(pageQueryPlanCustomerStatRequest.getBizId());
                break;
            case SALES_DEPARTMENT:
                planCustomerLoadListRequest.setOrgSalesDepartmentCode(pageQueryPlanCustomerStatRequest.getBizId());
                break;
            case SALES_CHANNEL:
                planCustomerLoadListRequest.setOrgSalesChannelCode(pageQueryPlanCustomerStatRequest.getBizId());
                break;
            case SALES_ORGANIZATION:
                planCustomerLoadListRequest.setOrgSalesOrganizationCode(pageQueryPlanCustomerStatRequest.getBizId());
                break;
            case BUSINESS_UNIT:
                planCustomerLoadListRequest.setOrgBusinessUnitCode(pageQueryPlanCustomerStatRequest.getBizId());
                break;
            default:
        }
        return planCustomerLoadListRequest;
    }

    private QueryPlanCustomerPercentRequest planCustomerQueryStatRequestConverter(QueryPlanCustomerStatRequest planCustomerStatRequest) {
        QueryPlanCustomerPercentRequest queryPlanCustomerPercentRequest = new QueryPlanCustomerPercentRequest();
        BeanUtils.copyProperties(planCustomerStatRequest, queryPlanCustomerPercentRequest);
        //如果登陆人为业务员
        if (planCustomerStatRequest.getIsSales()) {
            queryPlanCustomerPercentRequest.setEmployeeId(planCustomerStatRequest.getEmployeeId());
        } else {
            queryPlanCustomerPercentRequest.setEmployeeId(null);
        }
        return queryPlanCustomerPercentRequest;
    }

    private LoadPlanCustomerRequest loadSalesPlanCustomerRequestConverter(QueryPlanCustomerStatRequest queryPlanCustomerStatRequest) {
        LoadPlanCustomerRequest loadPlanCustomerRequest = new LoadPlanCustomerRequest();
        BeanUtils.copyProperties(queryPlanCustomerStatRequest, loadPlanCustomerRequest);
        return loadPlanCustomerRequest;
    }

    private PlanCustomer planCustomerConverter(SalesPlanStatCustomerSDO salesPlanCustomerStatSDO) {
        PlanCustomer planCustomer = new PlanCustomer();
        BeanUtils.copyProperties(salesPlanCustomerStatSDO, planCustomer);
        return planCustomer;
    }


}
